<template>
  <el-col :sm="24" :md="24">
    <i
      class="iconfont icon-shezhi pull-right widgetset hidden-print"
      @click.stop="dialogInputVisible = true"
    ></i>
    <i
      class="iconfont icon-shanchu pull-right widgetdel hidden-print"
      @click.stop="delWid(pzoption.wigdetcode)"
    ></i>
    <p style="FONT-SIZE: 16PX; MARGIN-BOTTOM: 5PX;" v-text="pzoption.title"></p>
    <el-input v-model="pzoption.value" style="display:none"></el-input>
    <div
      class="qj-tab-phone-items"
      v-for="(res,resIndex) in childpro.dataset"
      :key="'res_'+resIndex"
    >
      <div class="res-item">
        <div class="summary" @click.stop="res.show=!res.show">
          <span class="num">{{resIndex+1}}</span>
          <el-button @click.stop="editRow(res)" type="text">编辑</el-button>
          <el-button @click.stop="delRow(resIndex, childpro.dataset)" type="text">删除</el-button>
          <el-button @click.stop="copRow(resIndex, childpro.dataset)" type="text">复制</el-button>
          <i :class="!res.show?'el-icon-arrow-right':'el-icon-arrow-down'"></i>
        </div>
        <div
          v-show="res.show"
          class="item"
          v-if="isItem(name)"
          v-for="(val, name, index) in res"
          :key="name"
        >
          <span class="r-label">{{res[''.concat('colName_',name)]}}：</span>
          <span class="text">{{val}}</span>
        </div>
      </div>
    </div>
    <el-dialog :title="action==='add'?'添加':'编辑'" :visible.sync="dialogFormVisible" width="98%">
      <el-form :label-position="'top'" label-width="120px" :model="editForm">
        <el-form-item
          v-for="colForm in childpro.columdata"
          :label="colForm.colname"
          :key="colForm.colid"
        >
          <el-input
            style="width:100%"
            v-if="colForm.coltype=='el-input'"
            v-model="curForm[colForm.colid]"
            :disabled="childpro.disabled"
          ></el-input>
          <el-date-picker
            v-else-if="colForm.coltype=='el-date-picker'"
            value-format="yyyy-MM-dd"
            v-model="curForm[colForm.colid]"
            :disabled="childpro.disabled"
          ></el-date-picker>
          <el-select
            style="width:100%"
            v-else-if="colForm.coltype=='el-select'"
            v-model="curForm[colForm.colid]"
            placeholder="请选择"
            :disabled="childpro.disabled"
            filterable
            clearable
          >
            <el-option
              v-for="item in colForm.options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
          <span v-if="colForm.coltype=='el-lable'">{{curForm[colForm.colid]}}</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
    <el-button
      v-if="childpro.iskbj&&!childpro.disabled"
      type="primary"
      size="mini"
      class="mt10 pull-right"
      @click="addRow"
    >
      添加行
      <i class="el-icon-plus"></i>
    </el-button>
  </el-col>
</template>
<style>
</style>
<script>
module.exports = {
  props: [ 'pzoption', 'index' ],
  data () {
    return {
      curForm: {},
      resultForm: [],
      action: "",
      editResult: [],
      editForm: {},
      dialogFormVisible: false,
      dialogInputVisible: false,
      inputVisible: false,
      inputValue: '',
      childpro: {
        placeholder: "占位符",
        disabled: false,
        readonly: false,
        datatype: "0",
        nowcell: { rowindex: "0", colindex: "0", rowspan: "1", colspan: "1" },
        columdata: [],
        dataset: [],
        rowlen: 5,
        iskbj: true,
        tabname: "",
        hbdata: [],
        ishj: false,
        dynamicTags: [],
        rules: {
          required: false, message: '不能为空', type: "string"
        }
      }

    };
  },
  methods: {
    isItem: function (val) {
      return /^col\d+$/.test(val)
    },
    saveEdit: function () {
      var hasNullkey = this.hasNull()
      console.log(hasNullkey)
      if (hasNullkey) {
        this.$message.error("".concat(this.curForm[ ''.concat('colName_', hasNullkey) ], '不能为空！'))
        return
      }
      if (this.action === 'add') {
        this.childpro.dataset.push(this.curForm);
      }
      this.dialogFormVisible = false
    },
    hasNull: function () {
      for (var key in this.curForm) {
        if (this.curForm.hasOwnProperty(key)) {
          if (!this.curForm[ key ] && key != 'show') {
            return key
          }
        }
      }
      return false
      // for (let index = 0; index < list.length; index++) {
      //   var element = list[ index ];
      //   var cur = fun(element, index);
      //   if (cur) {
      //     return cur
      //   }
      // }
      // return false
    },

    genID: function () {
      var random = Math.floor(Math.random() * (90000 - 10000 + 1) + 10000);
      return random;
    },
    tableRowClassName ({ row, rowIndex }) {
      //把每一行的索引放进row
      row.index = rowIndex;
    },
    delWid: function (wigdetcode) {
      this.$root.nowwidget = {};
      _.remove(this.$root.FormData.wigetitems, function (obj) {
        return obj.wigdetcode == wigdetcode;
      });
    },
    senddata: function () {
      this.$emit('data-change', JSON.stringify(this.childpro), this.pzoption.wigdetcode);
    },
    handleClose: function (tag, el) {
      _.remove(el.options, function (obj) {
        return obj.value == tag.value;
      });
    },
    showInput: function (cindex) {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs[ "saveTagInput" + cindex ][ 0 ].$refs.input.focus();
      });
    },
    handleInputConfirm: function (el) {
      let inputValue = this.inputValue;
      if (inputValue) {
        el.options.push({ label: inputValue, value: inputValue });
        this.inputVisible = false;
        this.inputValue = '';
      }

    },

    addcol: function () {
      var colid = "col" + this.genID();
      var colindex = this.childpro.columdata.length + 1;
      this.childpro.columdata.push({ "colid": colid, "colname": "列" + colindex, "coltype": "el-input", "defvalue": "", "datatype": "1", "readonly": false, "field": "", "width": "", "ishj": false, "datasql": "", "istip": true, options: [], hbdata: "" });
      this.childpro.tabname = colid;
    },
    delfiled: function (queryitem) {
      var index = _.findIndex(this.childpro.columdata, function (obj) {
        return obj.colname == queryitem.colname;
      });
      this.childpro.columdata.splice(index, 1)

    },
    mangerel: function (components) {
      _.forEach(components, function (obj) {
        debugger;
        switch (obj.$attrs.coltype) {
          case "el-input-number":
            break;
          case "month":
            break;
          case "el-select":
            obj.$attrs.options = [ {
              value: '选项1',
              label: '黄金糕'
            }, {
              value: '选项2',
              label: '双皮奶'
            }, {
              value: '选项3',
              label: '蚵仔煎'
            }, {
              value: '选项4',
              label: '龙须面'
            }, {
              value: '选项5',
              label: '北京烤鸭'
            } ]
            break;
          default:
            return ""
        }
      })
    },
    addRow: function () {
      var temp = {};
      _.forEach(this.childpro.columdata, function (col) {
        temp[ col.colid ] = col.defvalue;
        temp[ ''.concat('colName_', col.colid) ] = col.colname
        temp.show = true
      })
      this.curForm = temp
      this.dialogFormVisible = true
      this.action = 'add'

    },
    copRow: function (index, rows) {
      var temp = JSON.stringify(rows[ index ]);
      rows.splice(index, 0, JSON.parse(temp));

    },
    delRow: function (index, rows) {
      rows.splice(index, 1);
    },
    editRow: function (row) {
      this.action = 'edit'
      this.curForm = row
      this.dialogFormVisible = true
    },
  
    objectSpanMethod: function ({ row, column, rowIndex, columnIndex }) {
      if (column.hasOwnProperty("label")) {
        try {
          var temp = _.find(this.childpro.columdata, function (obj) {
            return obj.colname == column.label
          }).hbdata;
          var hbs = temp.split(",");
          for (var i = 0; i < hbs.length; i++) {
            var hb = hbs[ i ].split('-');
            if (columnIndex == hb[ 0 ]) {
              if (rowIndex == hb[ 1 ]) {
                return {
                  rowspan: hb[ 2 ],
                  colspan: 1
                };
              }
              var tempar = [];
              for (var m = 1; m < hb[ 2 ] * 1; m++) {
                tempar.push(hb[ 1 ] * 1 + m);
              }
              if (tempar.indexOf(rowIndex) > -1) {
                return {
                  rowspan: 0,
                  colspan: 0
                };
              }
            }
          }

        } catch (e) {

        }

      }


    },

    getSummaries: function (param) {

      const { columns, data } = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[ index ] = '合计';
          return;
        }
        var col = _.find(this.childpro.columdata, function (obj) {
          return obj.colname == column.label && obj.ishj == true;
        })
        debugger;
        if (col) {
          var temphj = 0;
          _.forEach(data, function (obj) {
            if (obj[ col.colid ]) {
              temphj = temphj * 1 + obj[ col.colid ] * 1;
            }
          })
          sums[ index ] = temphj;
        } else {
          sums[ index ] = "";
        }

      });

      return sums;
      //const { columns, data } = param;
      //const sums = [];

      //columns.forEach((column, index) => {

      //if (index === 0) {
      //    sums[index] = '合计';
      //    return;
      //} else if (index == 4) {
      //    var col = _.find(this.pzoption.columdata, function (obj) {
      //        return obj.colname == column.label
      //    })
      //    debugger;
      //    var temphj = 0;
      //    _.forEach(data, function (obj) {
      //        if (obj[col.colid]) {
      //            temphj = temphj * 1 + obj[col.colid] * 1;
      //        }
      //    })
      //    sums[index] = temphj;
      //} else {
      //    sums[index] = "N/A";

      //}

      //});

      //return sums;

    },
    widchange: function (newWidth, oldWidth, column, event) {
      var pro = this;
      _.forEach(this.$root.FormData.wigetitems, function (wiget) {
        var temp = {};
        if (wiget.wigdetcode == pro.childpro.wigdetcode) {
          _.forEach(wiget.columdata, function (col) {
            if (column.label == col.colname) {
              col.width = newWidth;
            }
          })
        }
      })

    }
  },
  mounted: function () {
    var pro = this;
    pro.$nextTick(function () {
      if (pro.$root.addchildwig) {
        pro.$root.addchildwig();//不能缺少,dom加载完成
      }
      if (this.pzoption.childpro.nowcell) {
        this.childpro = this.pzoption.childpro
      }
    })

  },
  watch: {
    childpro: { //深度监听，可监听到对象、数组的变化
      handler (newV, oldV) {
        //if (this.childpro.dataset.length>0) {
        //}
        this.pzoption.value = JSON.stringify(this.childpro.dataset).replace(/null/g, '""');
        this.senddata();
      },
      deep: true
    }
  },
  created () {
    this.$nextTick(function () {
      // DOM 更新了
      // console.debug(this.$refs.refCol)
      // this.mangerel(this.$refs.refCol)
    })
  }
};
</script>
<style>
.qj-tab-phone-items .res-item {
  margin-bottom: 0.5rem;
  border: 1px solid #eee;
  padding: 0.5rem 1.5rem;
}
.qj-tab-phone-items .res-item .item {
  padding: 0.2rem 1.2rem;
}
.qj-tab-phone-items .res-item .summary .num {
  font-weight: 700;
  background-color: #409eff;
  width: 2rem;
  height: 2rem;
  display: inline-block;
  text-align: center;
  border-radius: 50%;
  color: #ffffff;
}
.qj-tab-phone-items .res-item .summary i {
  margin-left: 2rem;
}
.qj-tab-phone-items .res-item .r-label {
  font-size: 1rem;
  font-weight: 550;
}
.qj-tab-phone-items .res-item .text {
  color: #333;
}
</style>
